// loads a list of identities, stores then as JSON objects
// and adds some useful functions to help wrap the 
// Mozilla API for working with these objects.

var identities = function() {
	var self = this;
	
	self.identities = new Array();
	
	self.getIdentities = function(acct) {
		for(var i = 0; i < acct.identities.Count(); i++) {
			var id = acct.identities.QueryElementAt(i, Components.interfaces.nsIMsgIdentity);
			
			if(id.valid) {
				self.identities.push({
					nsIMsgIdentity: id,
					
					key: function() {
						if(!this.nsIMsgIdentity) {
							return null;
						}
						
						return this.nsIMsgIdentity.identityName;
					},
					
					name: function() {
						if(!this.nsIMsgIdentity) {
							return null;
						}
						
						if(this.nsIMsgIdentity.fullName && this.nsIMsgIdentity.fullName.length) {
							return this.nsIMsgIdentity.fullName + " <" + this.nsIMsgIdentity.email + ">";
						}
						
						return "<" +  this.nsIMsgIdentity.email + ">";
					},
					
					compose: function() {
						if(!this.nsIMsgIdentity) {
							return;
						}
						
						Components.classes["@mozilla.org/messengercompose;1"]  
							.getService(Components.interfaces.nsIMsgComposeService)
							.OpenComposeWindowWithParams(null, {
								type: Components.interfaces.nsIMsgCompType.New,
								identity: this.nsIMsgIdentity
							});
					}
				});	
			}
		}
	}
	
	self.load = function() {
		var acctMgr = Components.classes["@mozilla.org/messenger/account-manager;1"].getService(Components.interfaces.nsIMsgAccountManager);
		
		// see https://developer.mozilla.org/en/Thunderbird/Account_examples
		for(var i = 0; i < acctMgr.accounts.Count(); i++) {
			self.getIdentities(acctMgr.accounts.QueryElementAt(i, Components.interfaces.nsIMsgAccount));
		}
	}

	// load and sort the identities array at initialization
	self.load();
	// sort the identities descending
	self.identities.sort(function(x, y) {
		if(x.name() == y.name()) {
			return 0;
		}
		else if(x.name() > y.name()) {
			return -1;
		}
		
		return 1;
	});
}